package com.goambu.driver.autenticacion.view;

import java.io.IOException;

import org.apache.http.Header;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.NotificationManager;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;

import com.goambu.driver.GoAmbuDriverConstants;
import com.goambu.driver.autenticacion.controller.AutenticacionController;
import com.goambu.driver.autenticacion.entities.UsuarioBean;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.gcm.GoogleCloudMessaging;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;

public class PushNotificationActivity extends GPSTrackingActivity{
	private final static int PLAY_SERVICES_RESOLUTION_REQUEST = 9000;

	ProgressDialog prgDialog;
	RequestParams params = new RequestParams();
	GoogleCloudMessaging gcmObj;
	Context applicationContext;
	static String regId = "";

	AsyncTask<Void, Void, String> createRegIdTask;
	
	
	NotificationManager mNotificationManager;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		applicationContext = getApplicationContext();

		if (checkPlayServices()) {
			registerInBackground();
		}

		prgDialog = new ProgressDialog(this);
		// Set Progress Dialog Text
		prgDialog.setMessage("Cargando...");
		// Set Cancelable as False
		prgDialog.setCancelable(false);

		String registrationId = AutenticacionController.getInstance().getRegistrationId();

		// When Email ID is set in Sharedpref, User will be taken to
		// HomeActivity
		/*if (!registrationId.isEmpty()) {
			if (checkPlayServices()) {
				// Register Device in GCM Server
				registerInBackground();
			}
		}*/

	}

	private void registerInBackground() {
		new AsyncTask<Void, Void, String>() {
			@Override
			protected String doInBackground(Void... params) {
				String msg = "";
				try {
					if (gcmObj == null) {
						gcmObj = GoogleCloudMessaging
								.getInstance(applicationContext);
					}
					regId = gcmObj
							.register(GoAmbuDriverConstants.GOOGLE_PROJ_ID);
					msg = "Registration ID :" + regId;
					

				} catch (IOException ex) {
					msg = "Error :" + ex.getMessage();
				}
				return msg;
			}

			@Override
			protected void onPostExecute(String msg) {
				if (!regId.isEmpty()) {
					storeRegIdinSharedPref(applicationContext, regId);
					/*
					 * Toast.makeText( applicationContext,
					 * "Registered with GCM Server successfully.\n\n" + msg,
					 * Toast.LENGTH_SHORT).show();
					 */
				} else {
					Toast.makeText(
							applicationContext,
							"Reg ID Creation Failed.\n\nEither you haven't enabled Internet or GCM server is busy right now. Make sure you enabled Internet and try registering again after some time."
									+ msg, Toast.LENGTH_LONG).show();
				}
			}
		}.execute(null, null, null);
	}

	private void storeRegIdinSharedPref(Context context, String reg) {
		AutenticacionController.getInstance().storeRegIdinSharedPref(reg);
		regId = reg;
		Log.d("RegId", regId);
		storeRegIdinServer();
	}

	private void storeRegIdinServer() {
		/*new AsyncTask<Void, Void, String>() {
			@Override
			protected String doInBackground(Void... params) {
				Log.d("StoreRegIdInServer", regId);
				//AutenticacionController.getInstance().UpdateWorkerNotificationToken(regId);
				return "";
			}
			@Override
			protected void onPostExecute(String msg) {
				
			}
		}.execute(null, null, null);*/
		
		prgDialog.show();
		
		String path = GoAmbuDriverConstants.TESTSERVER_URL;
					
		params.put("regId", regId);
		Toast.makeText(applicationContext,
				regId,
				  Toast.LENGTH_LONG).show();
		// Make RESTful webservice call using AsyncHttpClient object
		AsyncHttpClient client = new AsyncHttpClient();
		client.post(path, params,
				new AsyncHttpResponseHandler() {
					// When the response returned by REST has Http
					// response code '200'
					@Override
					public void onSuccess(int arg0, String arg1) {
						// TODO Auto-generated method stub
						super.onSuccess(arg0, arg1);
						// Hide Progress Dialog
						prgDialog.hide();
						if (prgDialog != null) {
							prgDialog.dismiss();
						}
						
						  Toast.makeText(applicationContext,
						  "Reg Id shared successfully with Web App ",
						  Toast.LENGTH_LONG).show();
					}

					// When the response returned by REST has Http
					// response code other than '200' such as '404',
					// '500' or '403' etc
					
					@Override
					public void onFailure(Throwable arg0, String arg1) {
						// TODO Auto-generated method stub
						super.onFailure(arg0, arg1);
						
						// Hide Progress Dialog
						prgDialog.hide();
						if (prgDialog != null) {
							prgDialog.dismiss();
						}
						/*// When Http response code is '404'
						if (statusCode == 404) {
							Toast.makeText(applicationContext,
									"Requested resource not found",
									Toast.LENGTH_LONG).show();
						}
						// When Http response code is '500'
						else if (statusCode == 500) {
							Toast.makeText(applicationContext,
									"Something went wrong at server end",
									Toast.LENGTH_LONG).show();
						}
						// When Http response code other than 404, 500
						else {*/
							Toast.makeText(
									applicationContext,
									arg0.getMessage()+
									"Unexpected Error occcured! [Most common Error: Device might "
											+ "not be connected to Internet or remote server is not up and running], check for other errors as well",
									Toast.LENGTH_LONG).show();
						//}
					}
					
					
				});
	}

	private boolean checkPlayServices() {
		int resultCode = GooglePlayServicesUtil
				.isGooglePlayServicesAvailable(this);
		if (resultCode != ConnectionResult.SUCCESS) {
			if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) {
				GooglePlayServicesUtil.getErrorDialog(resultCode, this,
						PLAY_SERVICES_RESOLUTION_REQUEST).show();
			} else {
				Toast.makeText(
						applicationContext,
						"This device doesn't support Play services, App will not work normally",
						Toast.LENGTH_LONG).show();
				finish();
			}
			return false;
		} else {
			
			  Toast.makeText( applicationContext,
			  "This device supports Play services, App will work normally",
			  Toast.LENGTH_LONG).show();
			 
		}
		return true;
	}

	@Override
	protected void onResume() {
		super.onResume();
		//checkPlayServices();
	}
	
	// when closing the current activity, the service will automatically shut
	// down(disconnected).
	@Override
	public void onDestroy() {
		super.onDestroy();
		Log.e("Destroy Push", "Destroy Push");
	}

}